﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SmartDeviceProject9
{
    public partial class PickMtrlSerial : Form
    {
        public PickMtrlSerial()
        {
            InitializeComponent();
        }

        public Form ParentForm { get; set; }

        private bool closeNoEnsure = true;
        private void PickMtrlSerial_Closing(object sender, CancelEventArgs e)
        {

            if (closeNoEnsure)
            {
                if (MessageBox.Show("关闭后，当前数据将丢失，是否继续？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }
                else
                {
                    closeNoEnsure = false;
                    this.Close();

                }
            }
            else
            {

                e.Cancel = false;
            }
            ParentForm.Show();
        }
        /// <summary>
        /// 组织
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxCheckOrg_SelectedIndexChanged(object sender, EventArgs e)
        {
            //取出当前组织的所有仓库
            Type type = typeof(string);
            string org = cbxCheckOrg.SelectedValue as string;


            if (org != null && org != "")
            {
                DataTable table = new DataTable();
                table.Columns.Add("StkId", type);
                table.Columns.Add("name", type);
                //调出仓库
                cbxOutStock.DataSource = table;
                cbxOutStock.DisplayMember = "name";
                cbxOutStock.ValueMember = "StkId";
                List<Stk> listStk = Context.Orgs[org]._stks;
                foreach (Stk s in listStk)
                {
                    DataRow dr = table.NewRow();
                    dr["StkId"] = s.StkId;
                    dr["name"] = s.Name;
                    table.Rows.Add(dr);
                }
            }
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItem1_Click(object sender, EventArgs e)
        {
            if (bindDataSource.Rows.Count <= 0)
            {
                MessageBox.Show("保存失败,至少录入一条条码");
                return;
            }
            if (FPkValue == String.Empty)
            {
                MessageBox.Show("保存失败,备料单Id不可为空");
                return;
            }
            DataTable table = bindDataSource.Copy();
            DataSet DS = new DataSet();
            DS.Tables.Add(table);
            //'kefe54f9527a8445b9f9e006e712f9b42'  生产备料到简单生产领料单据唯一标示
            string onlyMark="kefe54f9527a8445b9f9e006e712f9b42";
            string messStr = Context.Service.SourceDirectTransfer(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, FPkValue, DS, onlyMark);
            if (messStr == null || messStr.Contains("保存成功"))
                ClearData();

            MessageBox.Show(messStr);
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        DataTable bindDataSource;
        DataTable DataGrid2Table;
        //源单主键
        string FPkValue=string.Empty;
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PickMtrlSerial_Load(object sender, EventArgs e)
        {
            Type type = typeof(string);

            //条码
            bindDataSource = new DataTable();
            bindDataSource.TableName = "条码列表";
            //源单单据体主键Id
            bindDataSource.Columns.Add(new DataColumn("ID", type));
            //机组   
            bindDataSource.Columns.Add(new DataColumn("生产机组"));
            bindDataSource.Columns.Add(new DataColumn("FMachine", type));
            //条码
            bindDataSource.Columns.Add(new DataColumn("FBarCode", type));
            bindDataSource.Columns.Add(new DataColumn("条码", type));
            //物料编码
            bindDataSource.Columns.Add(new DataColumn("FMaterialId", type));
            bindDataSource.Columns.Add(new DataColumn("原纸名称", type));
            //幅宽编码
            bindDataSource.Columns.Add(new DataColumn("FAuxPropId", type));
            bindDataSource.Columns.Add(new DataColumn("幅宽", type));
            //数量
            bindDataSource.Columns.Add(new DataColumn("Qty", type));
            bindDataSource.Columns.Add(new DataColumn("数量", type));
            //单位
            bindDataSource.Columns.Add(new DataColumn("UnitId", type));
            bindDataSource.Columns.Add(new DataColumn("单位", type));

            this.BillSubBody.DataSource = bindDataSource;


            #region 条码单据体视图设置

            DataGridTableStyle billView = new DataGridTableStyle();

            DataGridTextBoxColumn tc1 = new DataGridTextBoxColumn();
            tc1.Width = 58;
            tc1.HeaderText = "生产机组";
            tc1.MappingName = "生产机组";
            DataGridTextBoxColumn tc3 = new DataGridTextBoxColumn();
            tc3.Width = 60;
            tc3.HeaderText = "条码";
            tc3.MappingName = "条码";
            DataGridTextBoxColumn tc4 = new DataGridTextBoxColumn();
            tc4.Width = 70;
            tc4.HeaderText = "原纸名称";
            tc4.MappingName = "原纸名称";
            DataGridTextBoxColumn tc5 = new DataGridTextBoxColumn();
            tc5.Width = 40;
            tc5.HeaderText = "幅宽";
            tc5.MappingName = "幅宽";
            DataGridTextBoxColumn tc6 = new DataGridTextBoxColumn();
            tc6.Width = 45;
            tc6.HeaderText = "数量";
            tc6.MappingName = "数量";
            DataGridTextBoxColumn tc7 = new DataGridTextBoxColumn();
            tc7.Width = 30;
            tc7.HeaderText = "单位";
            tc7.MappingName = "单位";



            billView.GridColumnStyles.Add(tc1);
            billView.GridColumnStyles.Add(tc3);
            billView.GridColumnStyles.Add(tc4);
            billView.GridColumnStyles.Add(tc5);
            billView.GridColumnStyles.Add(tc7);
            billView.GridColumnStyles.Add(tc6);
            




            billView.MappingName = "条码列表";

            this.BillSubBody.TableStyles.Add(billView);
            #endregion
            


            //生产备料单明细

            DataGrid2Table = new DataTable();
            DataGrid2Table.TableName = "备料单列表";
            //明细Id
            DataGrid2Table.Columns.Add(new DataColumn("ID", type));
            DataGrid2Table.Columns.Add(new DataColumn("生产机组", type));
            DataGrid2Table.Columns.Add(new DataColumn("FMachine", type));
            DataGrid2Table.Columns.Add(new DataColumn("原纸名称", type));
            DataGrid2Table.Columns.Add(new DataColumn("FMaterialNum", type));
            DataGrid2Table.Columns.Add(new DataColumn("幅宽", type));
            DataGrid2Table.Columns.Add(new DataColumn("FAuxPropId", type));
            //幅宽名称
            DataGrid2Table.Columns.Add(new DataColumn("FAuxPropertyName", type));
            //DataGrid2Table.Columns.Add(new DataColumn("调入仓库", type));
            DataGrid2Table.Columns.Add(new DataColumn("需求量", type));
            DataGrid2Table.Columns.Add(new DataColumn("领料量", type));
            //是否锁定材质
            DataGrid2Table.Columns.Add(new DataColumn("FLockMaterial", type));
            DataGrid2Table.Columns.Add(new DataColumn("材质锁定", type));

            //是否对外材质
            DataGrid2Table.Columns.Add(new DataColumn("FIsForOut",type));
            //关联对外材质
            DataGrid2Table.Columns.Add(new DataColumn("FOutMaterialNum", type));
            

            this.BillBody.DataSource = DataGrid2Table;


            #region 生产备料明细视图设置

            DataGridTableStyle t = new DataGridTableStyle();

            DataGridTextBoxColumn c1 = new DataGridTextBoxColumn();
            c1.Width = 58;
            c1.HeaderText = "生产机组";
            c1.MappingName = "生产机组";
            DataGridTextBoxColumn c2 = new DataGridTextBoxColumn();
            c2.Width = 70;
            c2.HeaderText = "原纸名称";
            c2.MappingName = "原纸名称";
            DataGridTextBoxColumn c3 = new DataGridTextBoxColumn();
            c3.Width = 40;
            c3.HeaderText = "幅宽";
            c3.MappingName = "幅宽";
            DataGridTextBoxColumn c4 = new DataGridTextBoxColumn();
            c4.Width = 45;
            c4.HeaderText = "需求量";
            c4.MappingName = "需求量";
            DataGridTextBoxColumn c5 = new DataGridTextBoxColumn();
            c5.Width = 45;
            c5.HeaderText = "领料量";
            c5.MappingName = "领料量";

            DataGridTextBoxColumn c6 = new DataGridTextBoxColumn();
            c6.Width = 20;
            c6.HeaderText = "材质锁定";
            c6.MappingName = "材质锁定";

            //DataGridTextBoxColumn c9 = new DataGridTextBoxColumn();
            //c9.Width = 60;
            //c9.HeaderText = "调入仓库";
            //c9.MappingName = "调入仓库";


            t.GridColumnStyles.Add(c1);
            t.GridColumnStyles.Add(c2);
            t.GridColumnStyles.Add(c3);

            //t.GridColumnStyles.Add(c9);

            t.GridColumnStyles.Add(c4);
            t.GridColumnStyles.Add(c5);
            t.GridColumnStyles.Add(c6);

            


            t.MappingName = "备料单列表";
            this.BillBody.TableStyles.Add(t);

            #endregion
            

            //设置组织
            DataTable table = new DataTable();
            table.Columns.Add("OrgId", type);
            table.Columns.Add("Name", type);


            int i = -1;
            int selectIndex = -1;
            foreach (var org in Context.Orgs)
            {
                i++;
                DataRow row = table.NewRow();
                row["OrgId"] = org.Value.OrgId;
                row["Name"] = org.Value.Name;
                table.Rows.Add(row);
                if (org.Value.OrgId == Context.UserCurrentOrgId)
                {
                    selectIndex = i;
                }
            }
            this.cbxCheckOrg.DataSource = table;
            cbxCheckOrg.DisplayMember = "Name";
            cbxCheckOrg.ValueMember = "OrgId";
            if (selectIndex > -1)
            { 
                cbxCheckOrg.SelectedIndex=selectIndex;
                cbxCheckOrg_SelectedIndexChanged(null, null);
            
            }
        }

        /// <summary>
        /// 条码回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbxCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string s = this.tbxCode.Text.Trim();        //条码
                this.tbxCode.Text = string.Empty;
                this.tbxCode.Focus();
                if (string.IsNullOrEmpty(s) || s == "")
                    return;

                string checkNum = this.tbxPreBillNo.Text.Trim();    //当前生产备料单编号
                if (string.IsNullOrEmpty(checkNum) || checkNum == "")
                {
                    MessageBox.Show("请先录入生产备料单编号");
                    this.tbxCode.Text = string.Empty;
                    return;
                }
                string jz = cbxFMachine.SelectedValue as string;
                if (jz == null || jz == "")
                {
                    MessageBox.Show("请选择机组");
                    return;
                }

                string orgId = this.cbxCheckOrg.SelectedValue as string;
                string stockId = this.cbxOutStock.SelectedValue as string;
                if (orgId == null || orgId == "")
                {
                    MessageBox.Show("查找失败：当前用户无组织");
                    return;
                }
                if (stockId == null || stockId == "")
                {
                    MessageBox.Show("查找失败：请选仓库");
                    return;
                }
                #region 判断在不在缓存

                foreach (DataRow dsb in bindDataSource.Rows)
                {
                    if (Convert.ToString(dsb["FBarCode"]) == s)
                    {
                        MessageBox.Show("条码已存在");
                        return;
                    }
                }

                #endregion
                //  物料编码           物料名        条码      基础数量     基础单位       幅宽        芯径            密度
                //FMaterialId,  FMaterialId.Name, FBarCode,  FBaseQty,  FBaseUnitId,    FAuxPropId  ,FDiameter   ,   FDensity   
                DataSet dataSet = Context.Service.GetCodeDetail(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, s, orgId, stockId,true);
                if (dataSet != null)
                {
                    //选择的机组
                    string machine = this.cbxFMachine.SelectedValue as string;
                    bool isbool = true;
                    DataTable table = dataSet.Tables[0];
                    string rowMac;
                    string rowMater;
                    decimal LL;

                    foreach (DataRow dr in table.Rows)
                    {
                        string Mat = Convert.ToString(dr["FMaterialId"]);        //物料编码
                        string FK = Convert.ToString(dr["FAuxPropId"]);             //幅宽
                        decimal FKValue = dr["AuxpropValue"] is DBNull ? 0 : Convert.ToDecimal(dr["AuxpropValue"]);
                        string outMaterialNum=Convert.ToString(dr["FOutMaterialNum"]);  //关联对个材质
                        decimal dgFKValue;
                        //生产调拨单明细
                        foreach (DataRow row in DataGrid2Table.Rows)
                        {
                            //生产机组编号
                            rowMac=Convert.ToString( row["FMachine"]);
                            //物料
                            rowMater=Convert.ToString( row["FMaterialNum"]);
                            //领料量
                            LL = Convert.ToDecimal(row["领料量"]);
                            //是否锁定材质
                            bool lockMaterial =Convert.ToBoolean(row["FLockMaterial"]);
                            //幅宽值
                            dgFKValue = row["FAuxPropertyName"] is DBNull ? 0 : Convert.ToDecimal(row["FAuxPropertyName"]);
                            if (machine == rowMac && FKValue > dgFKValue && Convert.ToDecimal(row["需求量"]) > LL)
                            {
                                if ((lockMaterial && Mat == rowMater) || (!lockMaterial && outMaterialNum == Convert.ToString(row["FOutMaterialNum"]) &&outMaterialNum!="0"))
                                {
                                    isbool = false;

                                    row["领料量"] = LL + Convert.ToDecimal(dr["FBaseQty"]);
                                    //添加条码列表
                                    DataRow nrow = bindDataSource.NewRow();

                                    nrow["Id"] = row["Id"];
                                    nrow["生产机组"] = row["生产机组"];
                                    nrow["FMachine"] = row["FMachine"];

                                    nrow["条码"] = dr["FBarCode"];
                                    nrow["FBarCode"] = dr["FBarCode"];

                                    nrow["原纸名称"] = dr["FMaterialFName"];
                                    nrow["FMaterialId"] = Mat;

                                    nrow["幅宽"] = FK;
                                    nrow["FAuxPropId"] = FK;

                                    nrow["数量"] = Convert.ToDecimal(dr["FBaseQty"]).ToString("0.##");
                                    nrow["Qty"] = dr["FBaseQty"];

                                    nrow["单位"] = dr["FBaseUnitId"];
                                    nrow["UnitId"] = dr["FBaseUnitId"];

                                    bindDataSource.Rows.Add(nrow);
                                }
                                
                            }
                        }
                        if (isbool)
                        {
                            MessageBox.Show("未找到符合条码的明细信息");
                        }
                    }
                }
                else
                {
                    MessageBox.Show("未查到条码信息");
                }
            }
            
        }

        /// <summary>
        /// 清空所有数据
        /// </summary>
        private void ClearData()
        {
            //备料编号
            this.tbxCheckNum.Text = string.Empty;
            //当前单据编号
            this.tbxPreBillNo.Text = string.Empty;
            //生产备料单明细
            DataGrid2Table.Clear();
            //条码明细
            bindDataSource.Clear();
            //单据主键Id
            FPkValue = string.Empty;
        }
        /// <summary>
        /// 生产备料单取值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbxCheckNum_KeyUp(object sender, KeyEventArgs e)
        {
            #region 备料编号回车

            if (e.KeyCode == Keys.Enter)
            {
                string orgId = this.cbxCheckOrg.SelectedValue as string;
                string outStockId = this.cbxOutStock.SelectedValue as string;
                string billNo = this.tbxCheckNum.Text.Trim();
                if (string.IsNullOrEmpty(billNo) || billNo == "" || string.IsNullOrEmpty(orgId) || orgId=="")
                    return;
                DataSet dataS = Context.Service.ManufactureStock(Context.AccountId, Context.UserName, Context.Password, Context.LocalId, billNo, orgId, outStockId);
                if (dataS != null)
                {
                    //清空数据
                    ClearData();

                    //设置当前备料单编号
                    tbxPreBillNo.Text = billNo;
                    //设置组织
                    DataTable orgTable = (DataTable)this.cbxCheckOrg.DataSource;
                    
                    //主存主键
                    FPkValue = Convert.ToString(dataS.Tables[0].Rows[0]["Id"]);
                    //设置组织
                    int i = -1;
                    foreach (DataRow row in orgTable.Rows)
                    {
                        i++;
                        if (Convert.ToString(row["OrgId"]) == Convert.ToString(dataS.Tables[0].Rows[0]["FOrgId"]))
                        {
                            break;
                        }
                    }
                    if (i >= 0)
                    {
                        this.cbxCheckOrg.SelectedIndex = i;
                        //目地加载出仓库
                        cbxCheckOrg_SelectedIndexChanged(null, null);
                        //设置调出仓库
                        DataTable stockTable = (DataTable)this.cbxOutStock.DataSource;
                        i = -1;
                        foreach (DataRow row in stockTable.Rows)
                        {
                            i++;
                            if (Convert.ToString(row["StkId"]) == Convert.ToString(dataS.Tables[0].Rows[0]["FOutDepositoryId"]))
                            {
                                break;
                            }
                        }
                        if (i >= 0)
                        {
                            this.cbxOutStock.SelectedIndex = i;
                        }
                        Type type = typeof(string);
                        string macName;

                        //设置条码页签 生产机组
                        DataTable codeMac = new DataTable();
                        codeMac.Columns.Add("key", type);
                        codeMac.Columns.Add("name", type);

                        decimal dosage;
                        //生产备料单据体明细
                        foreach (DataRow row in dataS.Tables[1].Rows)
                        {
                            //                 备料单的需求量                       备料单的领料量   
                            dosage = Convert.ToDecimal(row["FPlanDosage"]) - Convert.ToDecimal(row["FActuralDosage"]);
                            if (dosage <= 0) continue;
                            DataRow dr = DataGrid2Table.NewRow();
                            //明细Id
                            dr["ID"] = row["Id"];
                            macName = MachineName(Convert.ToString(row["FMachine"]));
                            dr["生产机组"] = macName;
                            dr["FMachine"] = row["FMachine"];

                            dr["原纸名称"] = row["FMaterialName"];
                            dr["FMaterialNum"] = row["FRawMaterialNum"];

                            dr["幅宽"] = row["FAuxPropertyId"];
                            dr["FAuxPropId"] = row["FAuxPropertyId"];
                            //幅宽名称
                            dr["FAuxPropertyName"] = row["FAuxPropertyName"];


                            dr["需求量"] = dosage.ToString("0.##");
                            //dr["调入仓库"] = row["FInDepositoryName"];
                            dr["领料量"] = 0;

                            //是否锁定材质
                            dr["FLockMaterial"] = row["FLockMaterial"];
                            if (Convert.ToBoolean(row["FLockMaterial"]))
                                dr["材质锁定"] = "是";
                            else
                                dr["材质锁定"] = "否";


                            //是否对外材质
                            dr["FIsForOut"] = row["FIsForOut"];
                            //关联对外材质
                            dr["FOutMaterialNum"] = row["FOutMaterialNum"];

                            DataGrid2Table.Rows.Add(dr);


                            //生产机组
                            DataRow macRow = codeMac.NewRow();
                            macRow["key"] = row["FMachine"];
                            macRow["name"] = macName;
                            codeMac.Rows.Add(macRow);
                        }
                        
                        //生产机组
                        if (codeMac.Rows.Count > 0)
                        {
                            //去重
                            DataView dv = codeMac.DefaultView;
                            DataTable dt = dv.ToTable(true, new string[] { "key", "name" });

                            this.cbxFMachine.DataSource = dt;
                            cbxFMachine.DisplayMember = "name";
                            cbxFMachine.ValueMember = "key";
                            this.cbxFMachine.SelectedIndex = 0;
                        }
                    }

                }
                else
                {
                    MessageBox.Show("未查到 备料单编号 信息");
                }
            }


            #endregion
        }
        /// <summary>
        /// 生产机组名称
        /// </summary>
        /// <param name="machineKey">生产机组Key</param>
        /// <returns>生产机组名</returns>
        private string MachineName(string key)
        {
            string name=null;
            Context.Machines.TryGetValue(key, out name);
            return name;
        }
        /// <summary>
        /// 双击删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BillSubBody_DoubleClick(object sender, EventArgs e)
        {
            int index = this.BillSubBody.CurrentRowIndex;
            if (index != -1)
            {
                bindDataSource.Rows.RemoveAt(index);

            }
        }
        /// <summary>
        /// 仓库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbxOutStock_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}